from flask import g, jsonify
from flask import request

from info import db
from info.models import News, Comment, CommentLike, User
from info.utils.response_code import RET
from . import news_blue
from flask import render_template
from info.utils.common import user_login_data

"""
关注功能
"""


@news_blue.route("/followed_user", methods=["GET", "POST"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请登陆")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    # 获取到作者id
    other = User.query.get(user_id)

    # 关注
    if action == "follow":
        if other not in user.followed:
            user.followed.append(other)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg="已经关注了该用户")
    else:
        #         取消关注
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg="没有在我关注的人列表中")

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="ok")


"""
评论点赞
"""


@news_blue.route("/comment_like", methods=["GET", "POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errsmg="请登录")

    comment_id = request.json.get("comment_id")  # 评论编号
    news_id = request.json.get("news_id")  # 新闻id
    action = request.json.get("action")  # 动作

    # 根据评论id查询新闻
    comment = Comment.query.get(comment_id)

    # 添加点赞操作
    if action == "add":
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()

        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment.like_count += 1

    # 取消点赞
    else:
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()

        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="点赞成功")


"""
新闻评论
"""
@news_blue.route("/news_comment", methods=["GET", "POST"])
@user_login_data
def news_comment():
    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")  # 评论内容
    parent_id = request.json.get("parent_id")  # 回复评论的id

    news = News.query.get(news_id)

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请登录")



    #    评论就是把内容提交到数据库
    comment = Comment()
    comment.user_id = user.id  # 把用户id赋值给评论表id
    comment.news_id = news.id
    comment.content = comment_str  # 评论内容

    if parent_id:
        comment.parent_id = parent_id

    db.session.add(comment)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())



"""
新闻收藏
"""
@news_blue.route("/news_collect", methods=["GET", "POST"])
@user_login_data
def news_collect():
    user = g.user
    news_id = request.json.get("news_id")  # 新闻编号
    action = request.json.get("action")  # 动作:收藏/取消收藏
    news = News.query.get(news_id)  # 新闻查询出来

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这条新闻")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请登录")

    if action == "collect":
        # 收场新闻
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="收藏成功")


@news_blue.route("/<int:news_id>")
@user_login_data
def newss_detail(news_id):
    user = g.user

    """
        点击排行
        """
    news = News.query.order_by(News.clicks.desc()).limit(10)
    news_list = []
    for new_mode in news:
        news_list.append(new_mode.to_dict())

    """
    新闻详情数据
    """
    news = News.query.get(news_id)  # 获取新闻编号

    """
    新闻收藏
    """
    # 如果是第一次进来,那么肯定是没收藏,所以这个值默认就是false
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

    # 查询评论列表
    comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    comment_list = []
    comment_likes = []
    comment_like_ids = []

    if user:
        # 获取所有的点赞的评论
        comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
        #     取出所有的点赞的id
        comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

    for comment in comments:

        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    is_followed = False

    if news.user and user:
        if news.user in user.followed:
            is_followed = True

    data = {
        "user_info": user.to_dict() if user else None,
        "click_news_list": news_list,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "is_followed":is_followed,
        "comments": comment_list

    }

    return render_template("news/detail.html", data=data)
